package com.admin_system.controller;

import com.admin_system.entity.NoticeRead;
import com.admin_system.pojo.User;
import com.admin_system.service.NoticeReadService;
import com.admin_system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 公告已读记录控制器
 */
@RestController
@RequestMapping("/api/notice-read")
@Slf4j
public class NoticeReadController {

    @Autowired
    private NoticeReadService noticeReadService;
    
    @Autowired
    private UserService userService;

    /**
     * 标记公告为已读
     */
    @PostMapping("/mark/{noticeId}")
    public ResponseEntity<?> markNoticeAsRead(@PathVariable("noticeId") Long noticeId) {
        try {
            // 获取当前登录用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            
            // 通过用户名获取用户信息
            User user = userService.findByUsername(username);
            
            if (user == null) {
                log.error("标记公告已读失败：找不到用户 {}", username);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(Map.of("success", false, "message", "用户信息不存在"));
            }
            
            // 从用户对象中获取ID和姓名
            Long userId = user.getId() != null ? user.getId().longValue() : null;
            String userName = user.getFullName() != null && !user.getFullName().isEmpty() 
                    ? user.getFullName() : username;
            
            if (userId == null) {
                log.error("标记公告已读失败：用户ID为空，用户名 {}", username);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(Map.of("success", false, "message", "用户ID不存在"));
            }
            
            boolean success = noticeReadService.markNoticeAsRead(noticeId, userId, userName);
            
            if (success) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "公告已标记为已读"
                ));
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(Map.of("success", false, "message", "标记公告已读失败"));
            }
        } catch (Exception e) {
            log.error("标记公告已读失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "服务器错误：" + e.getMessage()));
        }
    }

    /**
     * 获取公告的已读记录
     */
    @GetMapping("/records/{noticeId}")
    public ResponseEntity<?> getNoticeReadRecords(@PathVariable("noticeId") Long noticeId) {
        try {
            List<NoticeRead> records = noticeReadService.getNoticeReadRecords(noticeId);
            return ResponseEntity.ok(records);
        } catch (Exception e) {
            log.error("获取公告已读记录失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "服务器错误：" + e.getMessage()));
        }
    }

    /**
     * 检查用户是否已读某公告
     */
    @GetMapping("/check/{noticeId}")
    public ResponseEntity<?> checkNoticeRead(@PathVariable("noticeId") Long noticeId) {
        try {
            // 获取当前登录用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            
            // 通过用户名获取用户信息
            User user = userService.findByUsername(username);
            
            if (user == null) {
                log.error("检查公告已读状态失败：找不到用户 {}", username);
                return ResponseEntity.ok(Map.of("success", true, "hasRead", false));
            }
            
            Long userId = user.getId() != null ? user.getId().longValue() : null;
            if (userId == null) {
                log.error("检查公告已读状态失败：用户ID为空，用户名 {}", username);
                return ResponseEntity.ok(Map.of("success", true, "hasRead", false));
            }
            
            boolean hasRead = noticeReadService.hasUserReadNotice(noticeId, userId);
            
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "hasRead", hasRead
            ));
        } catch (Exception e) {
            log.error("检查公告已读状态失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "服务器错误：" + e.getMessage()));
        }
    }

    /**
     * 获取用户未读的公告数量
     */
    @GetMapping("/unread-count")
    public ResponseEntity<?> getUnreadNoticeCount() {
        try {
            // 获取当前登录用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            
            // 通过用户名获取用户信息
            User user = userService.findByUsername(username);
            
            if (user == null) {
                log.error("获取未读公告数量失败：找不到用户 {}", username);
                return ResponseEntity.ok(Map.of("success", true, "count", 0));
            }
            
            Long userId = user.getId() != null ? user.getId().longValue() : null;
            if (userId == null) {
                log.error("获取未读公告数量失败：用户ID为空，用户名 {}", username);
                return ResponseEntity.ok(Map.of("success", true, "count", 0));
            }
            
            int count = noticeReadService.getUnreadNoticeCount(userId);
            
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "count", count
            ));
        } catch (Exception e) {
            log.error("获取未读公告数量失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "服务器错误：" + e.getMessage()));
        }
    }

    /**
     * 获取公告的未读用户列表（管理员权限）
     */
    @GetMapping("/unread-users/{noticeId}")
    public ResponseEntity<?> getNoticeUnreadUsers(@PathVariable("noticeId") Long noticeId) {
        try {
            log.info("接收到获取公告未读用户列表请求，公告ID: {}", noticeId);
            
            // 获取当前登录用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            log.info("当前请求用户: {}", username);
            
            // 检查用户是否有管理员权限
            boolean isAdmin = authentication.getAuthorities().stream()
                    .anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
            log.info("用户 {} 是否为管理员: {}", username, isAdmin);
            
            if (!isAdmin) {
                log.warn("非管理员用户尝试访问未读用户列表：{}", authentication.getName());
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                        .body(Map.of("success", false, "message", "权限不足"));
            }
            
            List<Map<String, Object>> unreadUsers = noticeReadService.getNoticeUnreadUsers(noticeId);
            log.info("成功获取公告[{}]的未读用户列表，共{}条记录", noticeId, unreadUsers.size());
            
            // 记录返回的数据结构
            if (!unreadUsers.isEmpty()) {
                Map<String, Object> firstUser = unreadUsers.get(0);
                log.info("未读用户列表第一条记录字段: {}", firstUser.keySet());
            }
            
            return ResponseEntity.ok(unreadUsers);
        } catch (Exception e) {
            log.error("获取公告未读用户列表失败，公告ID: " + noticeId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "服务器错误：" + e.getMessage()));
        }
    }
} 